<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item> -->
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col :span="4"
                v-show="isAdd">
          <el-button type="primary"
                     @click="addUser">添加新用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="dataShow"
                style="width:100%"
                border
                stripe>
        <el-table-column type="index"></el-table-column>

        <el-table-column prop="username"
                         label="用户名">
        </el-table-column>
        <el-table-column prop="password"
                         label="密码">
        </el-table-column>
        <el-table-column prop="email"
                         label="邮箱">
        </el-table-column>
        <el-table-column prop="tel"
                         label="手机号">
        </el-table-column>
        <el-table-column prop="role"
                         label="角色">
        </el-table-column>

        <el-table-column fixed="right"
                         label="操作"
                         :width="isAdd?100:50">
          <!-- <el-table-column label="操作"
                         width="100"> -->
          <template slot-scope="scope">
            <el-button type="text"
                       size="small"
                       @click="edit(scope.row._id,scope.row.username)">编辑</el-button>
            <el-button type="text"
                       size="small"
                       @click="remove(scope.row._id)"
                       v-if="isAdd">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!---分页--->
      <el-pagination background
                     layout="prev, pager, next"
                     :total="total"
                     :page-size="pageSize"
                     :pager-count="11"
                     :current-page='1'
                     @current-change="handleCurrentChange">
      </el-pagination>

    </el-card>
    <!--------添加新用户对话框--------->
    <el-dialog title="新加用户"
               :visible.sync="addShow"
               width="30%"
               @close="addDialogClosed">
      <el-form ref="addDataFormRef"
               :model="addForm"
               :rules='addUserRule'>
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话"
                      prop="tel">
          <el-input v-model="addForm.tel"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addShow = false">取 消</el-button>
        <el-button type="primary"
                   @click="addData">确 定</el-button>
      </span>
    </el-dialog>
    <!--------编辑用户对话框--------->
    <el-dialog title="编辑用户"
               :visible.sync="editShow"
               width="30%"
               @close="editDialogClosed">
      <el-form ref="editDataFormRef"
               :model="editForm"
               :rules='editUserRule'>
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="editForm.username"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="editForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话"
                      prop="tel">
          <el-input v-model="editForm.tel"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editShow = false">取 消</el-button>
        <el-button type="primary"
                   @click="editData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { isNumber } from '../plugins/validate'
export default {
  name: 'users',
  data () {
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }
    return {
      isAdd: true,
      role: '',
      names: '',
      addForm: {
        username: '',
        password: '',
        email: '',
        tel: '',

      },
      addUserRule: {
        username: [
          { required: true, message: '请输入用户名' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符' }
        ],
        // 验证密码是否合法
        password: [
          { required: true, message: '请输入登录密码' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符' }

        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
      },
      datas: [],
      //数据总条数
      total: 0,
      //当前页
      currentPage: 1,
      //一共多少页
      pageNum: 1,
      //当前页中的数据
      dataShow: [],
      //根据页数对数据分组，并存进每一页
      totalPage: [],
      //每页多少条
      pageSize: 5,
      //将数据转为数组
      dataArray: [],
      addShow: false,
      editForm: {
        username: '',
        password: 0,
        email: 0,
        tel: '',
        _id: ''

      },
      editUserRule: {
        // 验证密码是否合法
        password: [
          { required: true, message: '请输入登录密码' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
      },
      editShow: false,
    }
  },
  created () {

    this.findRole()
    this.findAll()
  },
  methods: {
    findRole () {
      this.role = window.sessionStorage.getItem('role')
      this.names = window.sessionStorage.getItem('names')
      if (this.role === '超级用户') {
        this.isAdd = true
      } else {
        this.isAdd = false
      }
    },
    addUser () {
      this.addShow = true
    },
    addData () {
      this.$refs.addDataFormRef.validate(valid => {
        if (!valid) return
        let url = '/api/addUser'
        this.$http.post(url, this.$qs.stringify(this.addForm)).then(res => {
          if (res.status === 200) {
            console.log(res.data)
            this.$common.succ(res.data)
            this.findAll()
            this.addShow = false
          } else {
            this.$common.fail('添加失败')
          }
        })
      })
    },
    addDialogClosed () {
      this.$refs.addDataFormRef.resetFields()
    },
    editDialogClosed () {
      this.$refs.editDataFormRef.resetFields()
    },
    findAll () {

      let url = '/api/findUser'
      this.$http.get(url, { params: { role: this.role } }).then(res => {
        if (res.status === 200) {
          this.datas = res.data
          this.total = res.data.length
          this.pageData()
        } else {
          console.log(err)
        }
      })

    },
    edit (id, name) {
      if (name !== this.names && this.role === '普通用户') {
        this.$common.fail('普通用户只能修改自己的信息')
        // alert('普通用户只能修改自己的信息')
        return
      }
      this.editShow = true
      let url = '/api/findOneUser'
      this.$http.post(url, this.$qs.stringify({ _id: id })).then(res => {
        if (res.status === 200) {
          this.editForm = res.data
          // this.compareForm = JSON.parse(JSON.stringify(this.editForm))
        }
      })
    },
    editData () {
      this.$refs.editDataFormRef.validate(valid => {
        if (!valid) return
        let url = '/api/updateUser'
        this.$http.post(url, this.$qs.stringify(this.editForm)).then(res => {
          if (res.status === 200) {
            this.$common.succ('恭喜，编辑成功！')
            this.findAll()
            this.editShow = false

          } else {
            this.$common.fail('编辑失败!')
          }
        })
      })

    },
    remove (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // });
        let url = '/api/deleteUser'
        this.$http.post(url, this.$qs.stringify({ _id: id })).then(data => {
          // if (res.status === 200) {
          this.$common.succ('删除成功！')
          this.findAll()
          // } else {
          // this.$common.fail('失败')
          // }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    pageData () {
      //计算页数
      this.pageNum = Math.ceil(this.datas.length / this.pageSize) || 1
      //根据页数对数据分组，并存进每一页
      for (let i = 0; i < this.pageNum; i++) {
        // 每一页都是一个数组 形如 [['第一页的数据'],['第二页的数据'],['第三页数据']]
        // 根据每页显示数量 将后台的数据分割到 每一页,假设pageSize为5， 则第一页是1-5条，即slice(0,5)，第二页是6-10条，即slice(5,10)...
        let das = []
        for (let j = 0; j < this.pageSize; j++) {
          if ((this.pageSize * i + j) < (this.datas.length)) {
            das[j] = this.datas[this.pageSize * i + j]
          }
        }
        this.totalPage[i] = das
      }
      this.dataShow = this.totalPage[this.currentPage - 1]
    },
    handleCurrentChange (newPage) {
      this.currentPage = newPage
      this.dataShow = this.totalPage[this.currentPage - 1]
    },
  }
}
</script>
<style scoped>
/* .el-card, */
.el-table {
  margin-top: 30px;
}
.el-table {
  margin-bottom: 30px;
}
</style>